package com.cjf.weather.weathercollection.service.service.impl;

import com.cjf.weather.weathercollection.service.service.WeatherDataCollectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author cjf
 * @description
 * @create 2019-03-30 17:22
 */
@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    private static final long TIME_OUT = 1800L;

    private static Logger logger = LoggerFactory.getLogger(WeatherDataCollectionServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void syncWeatherData(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        String key = url; // redis的key,redis以key存储
        String content = null; // json内容
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        // 使用httpclient进行请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            content = responseEntity.getBody();
            // 将数据写入到缓存，并设置多少秒失效
            valueOperations.set(url, content, TIME_OUT, TimeUnit.SECONDS);
        }
        logger.info("直接从api获取数据");
    }
}
